package cn.cdzdjd.service.impl;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;
import org.springframework.stereotype.Service;

import cn.cdzdjd.constant.BrowserConstant;
import cn.cdzdjd.constant.LocationRedirect;
import cn.cdzdjd.service.OpenEyeService;
import cn.cdzdjd.util.UrlUtil;
import cn.cdzdjd.vo.VideoInfoVO;
import kong.unirest.HttpResponse;
import kong.unirest.Unirest;

@Service
public class OpenEysServiceImpl implements OpenEyeService {
	private final String baseUrl = "https://proxy.eyepetizer.net/v1/content/item/get_item_detail_v2";

	// https://m.eyepetizer.net/u1/video-detail?video_id=324205&udid=347624bf011b4babad2769cc74dffedc&vc=7070010&vn=7.7.10&size=1080X2029&first_channel=xiaomi&last_channel=xiaomi&system_version_code=29&deviceModel=MI8
	@Override
	public VideoInfoVO getVideoInfo(String url) {
		try {
			Map<String, String> map = UrlUtil.convertUrlParamsToMap(new URL(url));
			HttpResponse<String> response = Unirest.post(baseUrl).header("origin", "https://m.eyepetizer.net")
					.header("referer", "https://m.eyepetizer.net/")
					.header("user-agent", BrowserConstant.USER_AGENT_MOBILE)
					.header("x-thefair-appid", "xfpa44crf2p70lk8").header("x-thefair-auth", "")
					.header("x-thefair-cid", "").header("x-thefair-forward-host", "https://api.eyepetizer.net")
					.header("x-thefair-ua",
							"EYEPETIZER_UNIAPP_H5/100000 (iphone;ios;16_6;zh-Hans-CN;h5;1.0.0;cn-bj;SOURCE_UNKNOWN;PHPSESSID;1170*2532;NETWORK_UNKNOWN) native/1.0")
					.header("Content-Type", "application/x-www-form-urlencoded").field("resource_type", "pgc_video")
					.field("resource_id", map.get("video_id")).asString();
			String jsonStr = response.getBody();
			JSONObject json = new JSONObject(jsonStr);
			if (json.getInt("code") == 0) {
				JSONObject videoInfo = json.getJSONObject("result").getJSONObject("video");
				String title = videoInfo.getString("title");
				String videoUrl = videoInfo.getString("play_url");
				String posterUrl = videoInfo.getJSONObject("cover").getString("url");
				List<String> videoList = new ArrayList<>();
				List<String> posterList = new ArrayList<>();
				// 开眼视频需要跳转一次，不然前端下载失败
				String videoRealUrl = LocationRedirect.getLocationMobile(videoUrl);
				videoList.add(UrlUtil.setHttps(videoRealUrl));
				posterList.add(UrlUtil.setHttps(posterUrl));
				return new VideoInfoVO(videoList, posterList, title, null);
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}

		return null;
	}

}
